package com.photoeditor.demo.ui.activity.subscribe;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.support.animation.SpringAnimation;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import com.billing.base.SkuWithType;
import com.billing.base.internal.SkuDetailsCacheManager;
import com.common.base.ComponentContext;
import com.common.base.ui.widget.ripple.RippleTextView;
import com.common.base.utils.thread.ThreadPool;
import com.photoeditor.R;
import com.photoeditor.demo.model.subscribe.manager.SVipController;
import com.photoeditor.demo.model.subscribe.manager.SkuManager;
import com.photoeditor.demo.model.subscribe.strategy.SVipStrategyManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.util.AndroidDevice;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static android.view.KeyEvent.KEYCODE_BACK;
import static com.photoeditor.demo.app.Global.PRIVACY_URL;
import static com.photoeditor.demo.app.Global.REFUND_URL;
import static com.photoeditor.demo.model.subscribe.manager.SkuManager.TYPE_MONTHLY;
import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_RETAIN_SUCCESS;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_MAIN_PAGE_TYPE;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_SUB_PACK;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_PAGE_TYPE_B;
import static com.photoeditor.demo.statistics.StatisticsConstant.VALUE_SUB_PACK_MONTH;
import static com.photoeditor.demo.statistics.StatisticsConstant.VALUE_SUB_PACK_YEAR;
import static com.photoeditor.demo.util.CheckPhoneHasBottomBarUtils.hasNavBar;

/**
 * Created by Lai on 2018/12/10 0010.
 */
public class SubscribeRetainDialogBActivity extends BaseSubscribeActivity {

    @Bind(R.id.tv_vip_dialog_tip)
    TextView mTvTip;
    @Bind(R.id.iv_vip_btn_anim)
    ImageView mIvBtnAnim;

    private String mFreeDaysYearly;
    private String mPrice;
    private int mSkuType;

    private String mStatisticPage;

    private AnimationDrawable mDrawable;
    private Animation animation;

    public static void startActivity(Activity activity, String entrance, int resultcode, SVipController.OnSubscribeCloseListener listener) {
        Intent intent = new Intent(activity, SubscribeRetainDialogBActivity.class);
        //统计表上说不统计入口
//        intent.putExtra(EXTRA_STATISTICS_ENTRANCE, entrance);
        intent.putExtra(EXTRA_TYPE,"B");
        intent.putExtra(EXTRA_IS_RETAIN,true);
        activity.startActivityForResult(intent, resultcode);
        sOnSubscribeCloseListener = listener;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_subscribe_retain_dialog_b;
    }

    @Override
    protected void initData() {
        super.initData();
        mSkuType = SVipStrategyManager.getInstance().getFirstSubscribeType();

        mFreeDaysYearly = SkuManager.getVipFreeDays(mSkuType);
        String skuYear = SkuManager.getSkuInfoLast(mSkuType);
        if (mSkuType == SkuManager.TYPE_MONTHLY) {
            mPrice = SkuManager.getVipPriceBMonth();
        } else {
            mPrice = SkuManager.getVipPriceBYear();
        }
        if (!TextUtils.isEmpty(skuYear)) {
            SkuWithType skuWithType = new SkuWithType(skuYear, BillingClient.SkuType.SUBS);
            SkuDetails cacheSkuDetails = SkuDetailsCacheManager.getInstance().getCacheSkuDetails(skuWithType);
            if (cacheSkuDetails != null) {
                if (mSkuType == SkuManager.TYPE_YEARLY) {
                    BigDecimal b1 = new BigDecimal(Float.toString(cacheSkuDetails.getPriceAmountMicros() / 1000000.0f));
                    BigDecimal b2 = new BigDecimal(12);
                    BigDecimal divide = b1.divide(b2, 2, RoundingMode.DOWN);
                    mPrice = cacheSkuDetails.getPriceCurrencyCode() + " " + b1;
                } else if (mSkuType == SkuManager.TYPE_MONTHLY) {
                    mPrice = cacheSkuDetails.getPrice();
                }
            }
        }
        initPriceView();

    }

    private SpringAnimation mTitleAnimationX, mTitleAnimationY;

    /**
     * 标题的动画
     */
    private void startTitleAnimation(View view) {
        //需求决定下面的参数
        float sti = 250f;//频率
        float dam = 0.175f;//时间 值越少，显示动画的时长越长
        float base = 0.95f;//字体基础大小 0.95%
        mTitleAnimationX = new SpringAnimation(view, SpringAnimation.SCALE_X, 1.0f);
        mTitleAnimationY = new SpringAnimation(view, SpringAnimation.SCALE_Y, 1.0f);
        mTitleAnimationX.getSpring().setStiffness(sti);
        mTitleAnimationX.getSpring().setDampingRatio(dam);
        mTitleAnimationX.setStartValue(base);

        mTitleAnimationY.getSpring().setStiffness(sti);
        mTitleAnimationY.getSpring().setDampingRatio(dam);
        mTitleAnimationY.setStartValue(base);
        mTitleAnimationX.start();
        mTitleAnimationY.start();
    }

    private void initPriceView() {
//        if (BuyUserManager.getInstance().isBuyUser()) {
//            mTvTip.setText(String.format(getResources().getString(R.string.vip_feature_tip), mFreeDaysYearly));
//        } else {
//            int hasPrice = R.string.vip_retain_tip;
//            int noPrice = R.string.vip_retain_tip_no_price;
        //拿不到策略时，默认展示年费
        int hasPrice = R.string.vip_year_tip;
        if (mSkuType == SkuManager.TYPE_MONTHLY) {
            hasPrice = R.string.vip_month_tip;
        }
        mTvTip.setText(String.format(getResources().getString(hasPrice), mPrice));
//        }

//        boolean showTip = false;

//        List<SVipStrategyBean.StrategyBeanConfig> configs = StrategyManager.getInstance().getStrategyConfig(CameraStrategyConstant.FUN_ID_SVIP, SVipStrategyBean.class);
//        boolean hasGotStrategy = (configs != null && !configs.isEmpty());
//        if (!hasGotStrategy) {
//            //没有拿到策略，展示默认文案
//            showTip = true;
//        }

//        String buyUserSource = BuyUserManager.getInstance().getBuyUserSource();
//        if (TextUtils.isEmpty(buyUserSource) || TextUtils.equals(buyUserSource, BuyUserManager.BUY_USER_UNKNOWN)) {
//            //未获取到渠道
//            //do nothing
//        } else {
//            //在获取到渠道的前提下，针对自然流量、本地语言为中文简体 、ip为中国、sim卡为中国、没sim卡等异常设备，显示文案
//
//            if (BuyUserManager.getInstance().getBuyUserType() == BuyUserManager.BuyType.TYPE_ORGANIC ||
//                    TextUtils.equals(RegionUtil.getCountry(), "CN") ||
//                    TextUtils.equals(NetInfoUtils.getInstance().getNetCountry(), "CN") ||
//                    TextUtils.equals(RegionUtil.getSimCountry(), "CN")) {
//                showTip = true;
//            } else if (TextUtils.isEmpty(SystemUtils.getSimCountry(ComponentContext.getContext()))) {
//                //没有sim卡的用户，需再判断该用户是否为买量，若是买量则不显示文案
//                if (BuyUserManager.getInstance().getBuyUserType() != BuyUserManager.BuyType.TYPE_ORGANIC) {
//                    showTip = false;
//                } else {
//                    showTip = true;
//                }
//            }
//        }

//        if (hasGotStrategy) {
//            //如果拿到了策略，还要看下服务器的配置
//            showTip = SVipStrategyManager.getInstance().canShowBottomTipText(SVipConstant.VIP_ENTRANCE_IN_APP);
//        }

//        mTvTip.setVisibility(showTip ? View.VISIBLE : View.GONE);
/*
        if (BuyUserManager.getInstance().isBuyUser()) {
            mTvTip.setText(String.format(getResources().getString(R.string.vip_feature_tip), mFreeDaysYearly));
        } else {
            int hasPrice = R.string.vip_retain_tip;
            int noPrice = R.string.vip_retain_tip_no_price;
            if (mSkuType == SkuManager.TYPE_MONTHLY) {
                hasPrice = R.string.vip_month_tip;
                noPrice = R.string.vip_month_tip_no_price;
            }
            if (TextUtils.isEmpty(mPrice)) {
                mTvTip.setText(String.format(getResources().getString(noPrice), mFreeDaysYearly));
            } else {
                mTvTip.setText(String.format(getResources().getString(hasPrice), mFreeDaysYearly, mPrice));
            }
        }

        if (SVipStrategyManager.getInstance().canShowBottomTipText(SVipConstant.VIP_ENTRANCE_RETAIN)) {
            mTvTip.setVisibility(View.VISIBLE);
        } else {
            mTvTip.setVisibility(View.GONE);
        }
*/
    }

    @Override
    protected void initView() {
//        TextView tvPrivacy = findViewById(R.id.tv_vip_privacy);
////        if (BuyUserManager.getInstance().isBuyUser()) {
////            tvPrivacy.setVisibility(View.GONE);
////        } else {
//        String privacyFull = getString(R.string.vip_privacy) + " | " + getString(R.string.vip_cancel_refund);
//        String privacy = getString(R.string.vip_privacy);
//        int privacySIndex = privacyFull.indexOf(privacy);
//        int privacyEIndex = privacySIndex + privacy.length();
//        String refund = getString(R.string.vip_cancel_refund);
//        int refundSIndex = privacyFull.indexOf(refund);
//        int refundEIndex = refundSIndex + refund.length();
//        SpannableStringBuilder builder = new SpannableStringBuilder(privacyFull);
//        builder.setSpan(new UnderlineSpan(), privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        builder.setSpan(new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//                AndroidDevice.startWebView(ComponentContext.getContext(), PRIVACY_URL);
//            }
//        }, privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        builder.setSpan(new UnderlineSpan(), refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        builder.setSpan(new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//                AndroidDevice.startWebView(ComponentContext.getContext(), REFUND_URL);
//            }
//        }, refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        tvPrivacy.setHighlightColor(getResources().getColor(R.color.transparent));
//        tvPrivacy.setLinkTextColor(tvPrivacy.getCurrentTextColor());
//        tvPrivacy.setMovementMethod(LinkMovementMethod.getInstance());
//        tvPrivacy.setText(builder);
//        }


        final TextView tvContent1 = findViewById(R.id.tv_retain_content_1);
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                startTitleAnimation(tvContent1);
            }
        }, 500);

//        FontUtil.setCustomFontMedium(tvContent1, tvContent2, tvContent3);

        mStatisticPage = StatisticsConstant.EVENT_RETAIN;

        ((RippleTextView) findViewById(R.id.btn_vip_layout)).setMask(R.drawable.button_vip_retain);

        animation = new TranslateAnimation(0, 0, 0, 10);
        animation.setDuration(900);
        animation.setRepeatCount(-1);

    }

    @Override
    protected boolean isPurchaseSuccess(List<Purchase> purchases) {
        boolean mIsYearlyVip = false;
        if (purchases != null) {
            for (Purchase purchase : purchases) {
                String sku;
                if (purchase != null && (sku = purchase.getSku()) != null) {
                    String[] yearlySkus = SkuManager.getSkuInfo(mSkuType);
                    for (String yearlySku : yearlySkus) {
                        if (TextUtils.equals(sku, yearlySku)) {
                            mIsYearlyVip = true;
                        }
                    }
                }
            }
        }

        return mIsYearlyVip;
    }

    @Override
    public void onBackPressed() {
        onCloseClick();
    }

    @OnClick(R.id.iv_vip_close)
    void onCloseClick() {
//        if (mFirstBackClick) {
//            //第一次点击返回不退出
//            mFirstBackClick = false;
//            return;
//        }
        //改了，一次点击生效
        finish();
        statisticBack(true);
    }

    @OnClick(R.id.btn_vip_layout)
    void onActionClick() {
        String[] normalSkus = SkuManager.getSkuInfo(mSkuType);
        if (normalSkus == null || normalSkus.length == 0 || TextUtils.isEmpty(normalSkus[normalSkus.length - 1])) {
            return;
        }
        String clickStatistic;
        if (mSkuType == SkuManager.TYPE_MONTHLY) {
            clickStatistic = StatisticsConstant.SUB_PACK_VALUE_MONTHLY;
            int subscribeType = SVipStrategyManager.getInstance().getFirstSubscribeType();
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RETAIN_CLICK,
//                    StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_MONTH,
//                    StatisticsConstant.KEY_AB_TYPE, StatisticsConstant.VALUE_B);
        } else {
            clickStatistic = StatisticsConstant.SUB_PACK_VALUE_ANNUAL;
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RETAIN_CLICK,
//                    StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_YEAR,
//                    StatisticsConstant.KEY_AB_TYPE, StatisticsConstant.VALUE_B);
        }
        subscribe(normalSkus[normalSkus.length - 1],
                clickStatistic);
    }

//    @OnClick(R.id.iv_close)
//    public void onCloseClicked(View view) {
//        if (mFirstBackClick) {
//            //第一次点击返回不退出
//            mFirstBackClick = false;
//            return;
//        }
//        onBackPressed();
//    }


    @Override
    protected void onResume() {
        super.onResume();
        if(hasNavBar(this)){//有虚拟键
            hideBottomUIMenu();
        }
        if (animation != null) {
            mIvBtnAnim.startAnimation(animation);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (animation != null) {
            mIvBtnAnim.clearAnimation();
        }
    }

    @Override
    public void finish() {
        setResult(RESULT_OK);
        super.finish();
        overridePendingTransition(R.anim.activity_no_animation, R.anim.activity_no_animation);
    }

    @Override
    protected void onPurchaseSuccess() {
        //测试
        StatisticsUtils.statisticGrowingIo(EVENT_RETAIN_SUCCESS,
                KEY_SUB_PACK, (mSkuType==TYPE_MONTHLY) ? VALUE_SUB_PACK_MONTH: VALUE_SUB_PACK_YEAR,
                KEY_MAIN_PAGE_TYPE, type,
                StatisticsConstant.KEY_SKU,sku);
    }

    @Override
    public String getStatisticPageStr() {
        return mStatisticPage;
    }

    @Override
    public String getSubscribeTypeStr() {
        return MAIN_PAGE_TYPE_B;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
